package com.tron.thread.synchronizedlist;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

public class SynchronizedListStart {
    public static void main(String[] args) {
        final ArrayList<String> strings = new ArrayList<>();
//        new ReadThread(strings).start();
//        new WriteThread(strings).start();
        final List<String> synchronizedList = Collections.synchronizedList(strings);
        new ReadThread(synchronizedList).start();
        new WriteThread(synchronizedList).start();

    }

    public static class ReadThread extends Thread{
        private List<String> list;

        public ReadThread(List<String> list) {
            this.list = list;
        }

        public void run() {
//            while (true) {
//                for (String s : list) {
//                    System.out.printf("%s\n",s);
//                }
//            }
            while (true) {
                synchronized (list) {
                    for (String s : list) {
                        System.out.printf("%s\n",s);
                    }
                }
            }
        }
    }

    public static class WriteThread extends  Thread{
        private List<String> list;
        public WriteThread(List<String> list){
            this.list = list;
        }

        public void run() {
            for (int i = 0; true; i++) {
                list.add(i+"");
                list.remove(0);
            }
        }
    }
}
